package cn.xlbweb.cli.shiro;

import cn.xlbweb.cli.common.enumerate.UserStatusEnum;
import cn.xlbweb.cli.model.User;
import cn.xlbweb.cli.common.constant.UserConsts;
import cn.xlbweb.cli.service.IPermissionService;
import cn.xlbweb.cli.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.*;

/**
 * @author: bobi
 * @date: 2019-09-16 20:23
 * @description:
 */
@Slf4j
public class CliRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private IUserService iUserService;

    @Autowired
    @Lazy
    private IPermissionService iPermissionService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("Shiro认证开始...");
        String username = authenticationToken.getPrincipal().toString();
        User user = iUserService.getUserByUsername(username);
        if (user == null) {
            throw new UnknownAccountException("账号不存在");
        }
        Integer status = Optional.ofNullable(user.getStatus()).orElse(-1);
        if (status == UserStatusEnum.DISABLE.getCode()) {
            throw new DisabledAccountException("账号已被冻结");
        }
        AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), ByteSource.Util.bytes(user.getUsername()), getName());
        log.info("Shiro认证结束...");
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("Shiro授权开始...");
        User user = (User) principalCollection.getPrimaryPrincipal();
        List<String> uriList;
        // 超级管理员则放行全部请求
        if (Objects.equals(user.getUsername(), UserConsts.ADMIN_USERNAME)) {
            uriList = iPermissionService.listPermissionUri(null);
        } else {
            uriList = iPermissionService.listPermissionUri(user.getId());
        }
        // 权限去重
        Set<String> uriSet = new HashSet<>(uriList);
        log.info("{}账号的权限列表:{}", user.getUsername(), uriSet);
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setStringPermissions(uriSet);
        log.info("Shiro授权结束...");
        return authorizationInfo;
    }

    public void clearAllCachedAuthorization() {
        super.getAuthorizationCache().clear();
    }
}
